package com.zhongyouyun.wx.wxapplet.lbyc.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongyouyun.admin.model.UserModel;
import com.zhongyouyun.admin.service.UserService;
import com.zhongyouyun.config.RedisConfig;
import com.zhongyouyun.config.WxMaConfig;
import com.zhongyouyun.other.annotation.SysLogAnnotation;
import com.zhongyouyun.other.model.Result;
import com.zhongyouyun.other.model.TokenUtil;
import com.zhongyouyun.wx.wxapplet.lbyc.vo.WxUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: shenyi
 * @Date: 2023-08-01
 * @Description:
 */
@RestController
@RequestMapping("wx/wxapplet/lbyc/wxUser")
@Api(value = "烟草灵宝-微信小程序登录操作", tags = {"烟草城区-微信小程序登录操作"})
public class WxUserLbycController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Resource
    private RedisConfig redisConfig;

    @GetMapping("/getCode")
    @ApiOperation(value = "微信小程序获取openid", notes = "微信小程序获取openid")
    public Result getCode(@ApiParam(name = "微信用户标识code", value = "code", required = true) @RequestParam(value = "code") String code) {
        WxMaService wxService = WxMaConfig.getMaService("wx0676fdb286d2b274");
        try {
            if (ObjectUtil.isNotEmpty(wxService)) {
                WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
                /*               wxService.getQrcodeService().qrCode()*/
                this.logger.info(session.getOpenid());
                //TODO 可以增加自己的逻辑，关联业务相关数据
                QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<UserModel>();
                userModelQueryWrapper.eq("open_id", session.getOpenid());
                List<UserModel> userModels = userService.selectList(userModelQueryWrapper);
                if (userModels.size() == 1) {
                    UserModel user = userModels.get(0);
                    Subject subject = SecurityUtils.getSubject();
                    UsernamePasswordToken token = new UsernamePasswordToken("mobile_" + user.getId().toString(), user.getPassword(), true);
                    subject = SecurityUtils.getSubject();
                    subject.login(token);
                    String u_token = TokenUtil.getToken(user.getUserName() + "_" + user.getId(), subject.getSession().getId().toString(), token.getHost());
                    user.setActivation("1");
                    userService.updateById(user);
                    user.setPassword("");
                    redisConfig.set(subject.getSession().getId().toString(), u_token, 60 * 60 * 60 * 2L);
                    redisConfig.set(u_token, user, 60 * 60 * 60 * 2L);
                    Map map = new HashMap();
                    map.put("WxOpenid", session.getOpenid());
                    map.put("WxUnionid", session.getUnionid());
                    map.put("isBind", true);
                    map.put("token", u_token);
                    map.put("userInfo", user);
                    return Result.builder().message("成功").status(0).data(map).build();
                } else if (userModels.size() == 0) {
                    Map map = new HashMap();
                    map.put("WxOpenid", session.getOpenid());
                    map.put("WxUnionid", session.getUnionid());
                    map.put("isBind", false);
                    map.put("token", "");
                    map.put("userInfo", "");
                    return Result.builder().message("成功").status(0).data(map).build();
                } else {
                    return Result.builder().message("获取失败").success(false).status(1).build();
                }
            }
            return Result.builder().message("获取失败").success(false).status(1).build();

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return Result.builder().message("获取失败").success(false).status(1).build();
        }
    }
//
//    @PostMapping("/verify")
//    @ApiOperation(value = "微信小程序验证是否绑定", notes = "微信小程序验证是否绑定")
//    public Result verify(@RequestBody WxUserVo wxUserVo) {
//        QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<UserModel>();
//        userModelQueryWrapper.eq("user_name", wxUserVo.getUserName());
//        userModelQueryWrapper.eq("true_name", wxUserVo.getTrueName());
//        UserModel user = userService.getOne(userModelQueryWrapper);
//        if (ObjectUtil.isNotEmpty(user)) {
//            if ("0".equals(user.getState())) {
//                return Result.builder().message("账号已锁定").status(1).success(false).build();
//            } else {
//                if (wxUserVo.getOpenId().equals(user.getOpenId())) {
//                    return Result.builder().message("微信已绑定!").success(false).status(1).build();
//                } else {
//                    return Result.builder().message("成功").status(0).build();
//                }
//            }
//        } else {
//            return Result.builder().message("账号密码错误!").success(false).status(1).build();
//
//        }
//    }

    @PostMapping("/login")
    @ApiOperation(value = "微信小程序用户绑定", notes = "微信小程序用户绑定")
    @SysLogAnnotation(operModul = "系统管理>>微信小程序", operType = "微信小程序用户登录", operDesc = "登入微信小程序")
    public Result login(@RequestBody WxUserVo wxUserVo) {
        Subject subject = SecurityUtils.getSubject();
        QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<UserModel>();
        userModelQueryWrapper.eq("user_name", wxUserVo.getUserName());
        userModelQueryWrapper.eq("true_name", wxUserVo.getTrueName());
        UserModel user = userService.getOne(userModelQueryWrapper);
        if (ObjectUtil.isNotEmpty(user)) {
            if ("0".equals(user.getState())) {
                return Result.builder().message("账号已锁定").status(1).success(false).build();
            } else {
                if (user.getOpenId() == null || user.getOpenId().equals("")) {
                    UsernamePasswordToken token = new UsernamePasswordToken("mobile_" + user.getId().toString(), user.getPassword(), true);
                    subject = SecurityUtils.getSubject();
                    subject.login(token);
                    String u_token = TokenUtil.getToken(user.getUserName() + "_" + user.getId(), subject.getSession().getId().toString(), token.getHost());
                    user.setActivation("1");
                    user.setUnionId(wxUserVo.getUnionId());
                    user.setOpenId(wxUserVo.getOpenId());
                    userService.updateById(user);
                    user.setPassword("");
                    redisConfig.set(subject.getSession().getId().toString(), u_token, 60 * 60 * 60 * 2L);
                    redisConfig.set(u_token, user, 60 * 60 * 60 * 2L);
                    Map map = new HashMap();
                    map.put("WxOpenid", wxUserVo.getOpenId());
                    map.put("WxUnionid", wxUserVo.getUnionId());
                    map.put("isBind", true);
                    map.put("token", u_token);
                    map.put("userInfo", user);
                    return Result.builder().message("登录成功").status(0).data(map).build();
                } else {
                    return Result.builder().message("该账号已被绑定!").success(false).status(1).build();
                }
            }
        } else {
            return Result.builder().message("此用户未加入协会!").success(false).status(1).build();
        }
    }

//    *
//     * 获取用户信息
//     *
//     * @return
//
//    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
//    public Result getUser() {
//        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
//        Subject subject = SecurityUtils.getSubject();
//        Object u = subject.getPrincipal();
//        if (u instanceof UserModel) {
//            UserModel user = (UserModel) subject.getPrincipal(); // 获取当前登录用户
//            resultMap.put("user", user);
//            resultMap.put("type", user.getType());
//            String u_token = (String) redisConfig.get(subject.getSession().getId().toString());
//            redisConfig.set(subject.getSession().getId().toString(), u_token, 60 * 60 * 60 * 2L);
//            return Result.builder().message("获取成功").status(0).success(true).data(resultMap).build();
//        }
//        return Result.builder().message("获取成功").status(0).success(true).data(resultMap).build();
//    }
//
//    *
//     * 退出
//     *
//     * @return
//
//    @RequestMapping(value = "/logout", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation(value = "退出", notes = "退出")
//    public Result logout() {
//        Subject subject = SecurityUtils.getSubject();
//        redisConfig.romove(subject.getSession().getId().toString());
//        //注销
//        subject.logout();
//        return Result.builder().message("注销成功").status(0).build();
//    }
//
//    *
//     * 修改密码
//     *
//     * @return
//
//    @PostMapping(value = "/updetebyPassword")
//    @ResponseBody
//    @ApiOperation(value = "修改密码", notes = "修改密码")
//    public Result updetebyPassword(@RequestBody WxUserVo wxUserVo) {
//        QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<UserModel>();
//        userModelQueryWrapper.eq("user_name", wxUserVo.getUserName());
//        userModelQueryWrapper.eq("open_id", wxUserVo.getOpenId());
//        UserModel user = userService.getOne(userModelQueryWrapper);
//        user.setPassword(SecureUtil.md5(wxUserVo.getPassWord()));
//        Boolean flag = userService.updateById(user);
//        if (flag) {
//            return Result.builder().message("成功").status(0).build();
//        } else {
//            return Result.builder().message("修改失败").success(false).status(1).build();
//        }
//    }
}
